// 引入文字样式
require('../fonts/iconfont.css')
require('../less/commCss/basic.css')
// 引入当前样式
require('../less/modify-info.less')
// 引入weui
require('../lib/weui/weui.min.css')
const weui = require('../lib/weui/weui.js')
// 引入公共js
const utils = require('../lib/commonJs/utils.js')
// 引入上传
const ajax = require('../lib/commonJs/http.js')

// 是否登录
utils.isLogin()

/**
 * 获取元素
 */
const iconPrev = document.querySelector('.icon-prev')
const userimg = document.querySelector('.overimg img')
const userimgFile = document.querySelector('#userimg-file')
const modifyInfoUserimg = document.querySelector('#modify-info-userimg')
const modifyInfoUsernameText = document.querySelector('#modify-info-username-text')
const modifyInfoSexText = document.querySelector('#modify-info-sex-text')
const modifyInfoTimerText = document.querySelector('#modify-info-timer-text')
const modifyInfoProvinceText = document.querySelector('#modify-info-province-text')
const modifyInfoCityText = document.querySelector('#modify-info-city-text')
const weuiTextarea = document.querySelector('.weui-textarea')
const weuiTextareaLength = document.querySelector('#weui-textarea-length')
const userupdata = document.querySelector('.userupdata')

// 回退
iconPrev.addEventListener('click', () => history.back())


/**
 * 渲染信息
 */
function showuserinfo() {
    const userinfo = JSON.parse(localStorage.getItem('userinfo'))
    // 渲染图像
    if (userinfo.imgurl) userimg.src = userinfo.imgurl;
    // 渲染昵称
    modifyInfoUsernameText.value = userinfo.nickname
    // 性别
    if (userinfo.gender) modifyInfoSexText.textContent = userinfo.gender
    // 生日
    if (userinfo.birthday) modifyInfoTimerText.textContent = userinfo.birthday.split('T')[0]
    // 省份
    if (userinfo.address) {
        let address = userinfo.address.split(',')
        modifyInfoProvinceText.textContent = address[0]
        modifyInfoCityText.textContent = address[1]
    }
    if (userinfo.sign) {
        weuiTextarea.value = userinfo.sign
        weuiTextareaLength.textContent = userinfo.sign.length
    }
}
showuserinfo()


// 上传图像
modifyInfoUserimg.addEventListener('click', function () {
    userimgFile.click()
})
userimgFile.addEventListener('change', function () {
    // 获取文件
    let img = this.files[0];
    // 上传
    ajax.$updateFile('/users/upload', 'imgurl', img, res => {
        if (res.data) userimg.src = 'http://139.9.177.51:8099' + res.data
    })
})

/**
 * 性别
 */
document.querySelector('#modify-info-sex').addEventListener('click', function () {
    weui.picker([{
        label: '女',
        value: 0
    }, {
        label: '男',
        value: 1
    }, {
        label: '其他',
        value: 2
    }], {
        onConfirm: function (result) {
            modifyInfoSexText.textContent = result[0].label
        },
        title: '性别'
    });
});

/**
 * 时间
 */
document.querySelector('#modify-info-timer').addEventListener('click', function () {
    weui.datePicker({
        start: 1900,
        end: new Date().getFullYear(),
        onConfirm: function (result) {
            let timerArr = [result[0].value, utils.zero(result[1].value), utils.zero(result[2].value)].join('-')
            modifyInfoTimerText.textContent = timerArr
        },
        title: '时间'
    });
});



/**
 * 处理城市省份数据
 */
function disposeMsg(arr) {
    let province = arr.map(function (item) {
        return {
            label: item.name,
            value: item.addressId
        }
    })
    return province
}

/**
 * 处理省份
 */
let province = null;

function getProvince() {
    ajax.$http.get('/address/province', function ({
        data
    }) {
        province = disposeMsg(data)
    })
}
getProvince()

/**
 * 省份
 */
let selectProvince = localStorage.getItem('selectProvince');
document.querySelector('#modify-info-province').addEventListener('click', function () {
    weui.picker(province, {
        onConfirm: function (result) {
            selectProvince = result[0].value
            localStorage.setItem('selectProvince', selectProvince)
            modifyInfoProvinceText.textContent = result[0].label
            modifyInfoCityText.textContent = '未选择'
            getCity()
        },
        title: '省份',
        defaultValue: [selectProvince]
    });
});
/**
 * 处理城市
 */
let city = null;

function getCity() {
    ajax.$http.get(`/address/city/${selectProvince}`, function ({
        data
    }) {
        if (data) city = disposeMsg(data)
    })
}
getCity()
/**
 * 城市
 */
document.querySelector('#modify-info-city').addEventListener('click', function () {

    if (city) {
        weui.picker(city, {
            onConfirm: function (result) {
                modifyInfoCityText.textContent = result[0].label
            },
            title: '城市'
        });
    } else {
        utils.toast('fail', '请选择省份')
    }
});

/**
 * 限制个人简介字数
 */

weuiTextarea.addEventListener('input', function () {
    if (this.value.length > 200) {
        this.value = this.value.substring(0, 200);
        return
    };
    weuiTextareaLength.textContent = this.value.length
})

/**
 * 保存用户信息
 */
const userId = JSON.parse(localStorage.getItem('userId'))
userupdata.addEventListener('click', function () {
    let userinfo = {
        "imgurl": userimg.src,
        "nickname": modifyInfoUsernameText.value,
        "gender": modifyInfoSexText.textContent,
        "birthday": modifyInfoTimerText.textContent,
        "address": [modifyInfoProvinceText.textContent, modifyInfoCityText.textContent],
        "sign": weuiTextarea.value,
        "userId": userId
    }
    console.log(userinfo);
    ajax.$http.post('/users/userEdit', userinfo, function ({
        status
    }) {
        console.log(status);
        if (status === 0) {
            location.href = './myhome.html'
        }
    })
})